// user.service.ts
import { Injectable } from "@nestjs/common";
import { DataSource, Repository } from "typeorm";
import { UsersEntity } from "common/lib/entities/user.entity";
import { InjectDataSource, InjectRepository } from "@nestjs/typeorm";
import { ToolsService } from "common/lib/utils/tools.service";
import { CreateUserDto } from "common/lib/dto/create-user.dto";
import { v4 as uuidv4 } from "uuid";
import { UpdateUserDto } from "common/lib/dto/update-user.dto";

@Injectable()
export class UserService {
  @InjectRepository(UsersEntity)
  private readonly usersRepository: Repository<UsersEntity>;

  @InjectDataSource()
  private readonly dataSource: DataSource;

  constructor() {}

  async findAll() {
    try {
      const res = await this.usersRepository
        .createQueryBuilder("user")
        .select()
        .getManyAndCount();
      return res;
    } catch (error) {
      ToolsService.fail(error);
    }
  }

  async findOne(id: string) {
    try {
      let res = await this.usersRepository.findOne({
        where: {
          id:Number(id),
        },
      });
      return res;
    } catch (error) {
      ToolsService.fail(error);
    }
  }

  async validateUser(userinfo): Promise<any> {
    const { username, password } = userinfo;
    const user = await this.usersRepository
      .createQueryBuilder('UsersEntity')
      .where('UsersEntity.username = :username', { username })
      .getOne();
    if (!user) ToolsService.fail('用户名不正确');
    //使用bcryptjs验证密码
    if (password != user.password) {
      ToolsService.fail('密码不正确');
    }
    return user;
  }

  async create(createUserDto: CreateUserDto) {
    const queryRunner = this.dataSource.createQueryRunner();
    try {
      const manager = await queryRunner.manager; //使用事务保存到副表
      const user = new UsersEntity();
      user.username = createUserDto.username;
      user.password = createUserDto.password;
      console.log("user", user);
      await manager.save(user);
      return user;
    } catch (error) {
      ToolsService.fail(error);
    } finally {
      // 关闭查询运行器
      await queryRunner.release();
    }
  }

  async update(updateUserDto: UpdateUserDto) {
    const queryRunner = this.dataSource.createQueryRunner();
    try {
      const manager = await queryRunner.manager; //使用事务
      const user = await manager
        .getRepository(UsersEntity)
        .createQueryBuilder("user")
        .where("user.id = :id", {
          id: updateUserDto.id,
        })
        .getOne();

      if (!user) {
        throw new Error("用户不存在");
      }
      user.username = updateUserDto.username;
      user.password = updateUserDto.password;
      await manager.save(user);
      return user;
    } catch (error) {
      ToolsService.fail(error);
    } finally {
      // 关闭查询运行器
      await queryRunner.release();
    }
  }

  async remove(id: string) {
    // 获取连接并创建新的queryRunner
    const queryRunner = this.dataSource.createQueryRunner();
    try {
      const manager = await queryRunner.manager; //使用事务保存到副表
      const userRepository = manager.getRepository(UsersEntity);
      await userRepository
        .createQueryBuilder("user")
        .delete()
        .where("user.id = :id", { id: id })
        .execute();

      return 1;
    } catch (error) {
      console.log("删除，取消事务");
      await queryRunner.rollbackTransaction(); //出错回滚
      ToolsService.fail(error);
    } finally {
      await queryRunner.release(); //释放
    }
  }
}
